package se.peterbjorkman.android.trafikkamera;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import se.peterbjorkman.android.trafikkamera.DownloadImageTask.Callback;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.LinearLayout.LayoutParams;

public class ImageDownloadingAdapter extends BaseAdapter {
   
    private List<CameraView> mViews;

    public ImageDownloadingAdapter(Context c, List<CameraGalleryActivity.CameraInfo> infos) {
        mViews = new ArrayList<CameraView>(infos.size());
        
        for (int i = 0; i < infos.size(); i++) {
			final CameraView view = new CameraView(c);
			view.setLayoutParams(new Gallery.LayoutParams(
	                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	        
			final CameraGalleryActivity.CameraInfo info = infos.get(i); // TODO use for each?
			mViews.add(view);
		    // TODO Description
			view.setDescription(info.name);
			if (info.drawable == null)
				startBackgroundDownload(c, view, info);
			else{
				view.setImage(info.drawable);
				view.setModifiedText(info.lastModified.toLocaleString());			
			}
		}
    }

	private void startBackgroundDownload(Context c, final CameraView view,
			final CameraGalleryActivity.CameraInfo info) {
		DownloadImageTask task = new DownloadImageTask(c, new Callback() {
			
			@Override
			public void statusCallback(String status) {
				view.setProgressStatus(status);
			}
			
			@Override
			public void progressCallback(int done, int total) {
				view.setProgress(done, total);	
			}
			
			@Override
			public void modifiedTimeCallback(Date date) {
				view.setModifiedText(date.toLocaleString());
				info.lastModified = date;
			}
			
			@Override
			public void imageCallback(BitmapDrawable drawable) {
				view.hideAllProgressIndication();
				view.setImage(drawable);
				info.drawable = drawable;
			}
		});
		
		task.execute(info.url);
	}

    public int getCount() {
        return mViews.size();
    }

    public Object getItem(int position) {
        return position; // TODO implement
    }

    public long getItemId(int position) {
        return position; // TODO implement
    }

    public View getView(int position, View convertView, ViewGroup parent) {
    	return mViews.get(position);
    }
}